'use strict'


var userName = document.querySelector('input#userName');
var roomName = document.querySelector('input#roomName');
var sendContent = document.querySelector('input#sendContent');
var connection = document.querySelector('button#connection');
var send = document.querySelector('button#send');
var content = document.querySelector('textarea#content');

var start = document.querySelector('button#start');
var hangup = document.querySelector('button#hangup');
var localVideo = document.querySelector('video#localVideo');
var remoteVideo = document.querySelector('video#remoteVideo');

var pc;
var user, room;
var socket;
var localStream;
var state = 'wait';

send.onclick = () => {

    var data = user + ":" + sendContent.value;
    socket.emit('message', room, data);

    sendContent.value = '';
};

function conn() {
    socket = io.connect();

    //收消息
    socket.on('joined', (room, user) => {
        console.log('接收到joined消息', room, user);
        state = 'joined';
        createPeerConnection();
        start.disabled = true;
        hangup.disabled = false;
        
    });
    socket.on('otherjoin', (room, user) => {
        console.log('接收到otherjoin消息', room, user);

        //如果当前是第一个joined未绑定则重新连接PeerConnection
        if (start == 'joined_unbind') {
            createPeerConnection();
        }

        //有人加入开始进入媒体协商进行连接
        state = 'joined_conn';

        call();

    });
    socket.on('full', (room) => {
        console.log('接收到full消息', room);
        state = 'leaved';
        socket.disconnect();
        start.disabled = false;
        hangup.disabled = true;
    });
    socket.on('leaved', (room, user) => {
        console.log('接收到leaved消息', room, user);
        state = 'leaved';
        socket.disconnect();
        start.disabled = false;
        hangup.disabled = true;
    });
    socket.on('bye', (room, user) => {
        console.log('接收到bye消息', room, user);
        //对方离开，进入未绑定状态
        state = 'joined_unbind';
        //关闭掉PC
        closePeerConnection();
    });
    socket.on('message', (room, user, data) => {
        console.log('接收到message消息', room, user, data);

        if (data) {
            if (data.type == 'offer') {
                pc.setRemoteDescription(new RTCSessionDescription(data));
                pc.createAnswer()
                    .then(getAnswer)
                    .catch(handleAnswerError);

            } else if (data.type == 'answer') {
                pc.setRemoteDescription(new RTCSessionDescription(data));
            } else if (data.type == 'candidate') {
                var candidate = new RTCIceCandidate({
                    sdpMLineIndex: data.label,
                    candidate: data.candidate
                });

                pc.addIceCandidate(candidate);
            }
            else {
                console.error('信息错误');
            }
        }
    });


    room = '111111';
    user = userName.value;

    //发送消息 加入房间
    socket.emit('join', room);
}

function leave() {
    if (socket) {
        socket.emit('leave', room);
    }

    closePeerConnection();
    closeLocalMedia();

    start.disabled = false;
    hangup.disabled = true;

}

//获取媒体流
function getMediaSteam(stream) {
    localVideo.srcObject = stream;
    localStream = stream;

    conn();
}

//绑定错误
function handleError(err) {
    console.error('错误:' + err);
}

//绑定错误
function handleOfferError(err) {
    console.error('handleOfferError错误:' + err);
}

//绑定错误
function handleAnswerError(err) {
    console.error('handleAnswerError错误:' + err);
}

function getRemoteStream(e) {
    remoteVideo.srcObject = e.streams[0];
}

function getAnswer(desc) {
    pc.setLocalDescription(desc);

    //发送desc到信令服务器 
    sendMessage(room, desc);
}

function sendMessage(roomId, data) {
    if (socket) {
        socket.emit('message', roomId, data);
    }
}

function getOffer(desc) {
    pc.setLocalDescription(desc);
    //发送desc到信令服务器
    sendMessage(room, desc);
}

function call() {
    if (state == 'joined_conn') {
        if (pc) {
            //创建媒体sdp的属性中是否使用接受音视频
            var offerOptions = {
                offerToReceiveAudio: 0,
                offerToReceiveVideo: 1
            };

            pc.createOffer(offerOptions)
                .then(getOffer)
                .catch(handleOfferError);
        };
    }
}

//开始采集本地数据并且设置localDiscri
start.onclick = () => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.error("不支持");
        return;
    }

    //只采集视频
    var constraints = {
        video: true,
        audio: false
    }

    navigator.mediaDevices.getUserMedia(constraints)
        .then(getMediaSteam)
        .catch(handleError);

};

function createPeerConnection() {
    if (!pc) {
        var pcConfig = {
            'iceServices': [{
                'urls': 'stun:stun.l.google.com:19302'
            }]
        };
        pc = new RTCPeerConnection(pcConfig);

        pc.onicecandidate = (e) => {
            if (e.candidate) {
                //发送诶对端
                sendMessage(room, {
                    type: 'candidate',
                    label: e.candidate.sdpMLineIndex,
                    id: e.candidate.sdpMid,
                    candidate: e.candidate.candidate
                })
            }
        };

        //远端数据流监听
        pc.ontrack = (e) => {
            remoteVideo.srcObject = e.streams[0];
        };
    }

    if (localStream) {
        localStream.getTracks().forEach((track) => {
            pc.addTrack(track, localStream);
        });
    }
}

//关闭Pc
function closePeerConnection() {
    if (pc) {
        pc.close();
        pc = null;
    }
}

//关闭本地媒体流
function closeLocalMedia() {
    if (localStream && localStream.getTracks()) {
        localStream.getTracks().forEach((track) => {
            track.stop();
        });
    }

    localStream = null;
}


// call.onclick = () => {
//     pc1 = new RTCPeerConnection();
//     pc2 = new RTCPeerConnection();

//     pc1.onicecandidate = (e) => {
//         pc2.addIceCandidate(e.candidate);
//     };

//     pc2.onicecandidate = (e) => {
//         pc1.addIceCandidate(e.candidate);
//     }

//     pc2.ontrack = getRemoteStream;

//     localStream.getTracks().forEach((track) => {
//         pc1.addTrack(track, localStream);
//     });






hangup.onclick = () => {

    leave();



};